import Constant from 'src/config/Constant';
import { v4 as uuidv4 } from 'uuid';
import * as crypto from 'crypto';
import * as dayjs from 'dayjs';
import { ManipulateType } from 'dayjs';
import * as os from "os";

const Utils = {
    // 唯一ID
    guid: (): string => {
        const guidWithHyphens = uuidv4(uuidv4()); // 生成带连字符的 GUID
        const guidWithoutHyphens = guidWithHyphens.replace(/-/g, ''); // 去除连字符
        return guidWithoutHyphens;
    },
    // 获取 salt
    getSalt: (): string => {
        return crypto.randomBytes(5).toString('hex');
    },
    // 密码 MD5 加密
    MD5: (str: string, salt: string): string => {
        const md5 = crypto.createHash('md5');
        md5.update(str + salt);
        return md5.digest('hex');
    },
    // 电话格式验证
    isPhone: (mobile: string): boolean => {
        if (!mobile) {
            return false;
        }
        return (/^1[3456789]\d{9}$/.test(mobile));
    },
    // redis token
    redisTokenKey: (str: string): string => {
        return `${Constant.redis_prefix}token-${str}`;
    },
    toJSON: (str: string) => {
        try {
            return JSON.parse(str)
        } catch (e) {
            return ''
        }
    },
    getDateByNow: (num: number, type: ManipulateType = 'day', format: string = 'YYYY-MM-DD'): string => {
        return dayjs().add(num, type).format(format)
    },
    // 将枚举转换为数组对象
    enumToArray(enumObject: any, fn: Function): { key: string | number; value: string }[] {
        return Object.keys(enumObject).reduce((result, key) => {
            const num = parseInt(key)
            if (isNaN(num)) {
                result.push({
                    key: fn(enumObject[key]),
                    value: enumObject[key]
                })
            }
            return result
        }, []);
    },
    ipv4() {
        // 获取当前主机 IPV4 地址
        const networkInterfaces = os.networkInterfaces();
        const ipv4Address = networkInterfaces["以太网"].filter(
            (_) => _.family === "IPv4"
        )[0].address;
        return ipv4Address
    }
};

export default Utils